package com.zh.equipment.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zh.common.controller.BaseController;
import com.zh.common.utils.HttpClient;
import com.zh.common.utils.PageUtils;
import com.zh.common.utils.Query;
import com.zh.common.utils.R;
import com.zh.device.domain.HardwareDO;
import com.zh.device.service.HardwareService;
import com.zh.device.service.RedisDeviceService;
import com.zh.equipment.domain.DeviceBindingRelaDO;
import com.zh.equipment.domain.DeviceExampleDO;
import com.zh.equipment.service.DeviceBindingRelaService;
import com.zh.equipment.service.DeviceExampleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 设备实例使用
 *
 * @author 马广洋
 * @email 54925881@qq.com
 * @date 2019-08-13 15:18:34
 */

@Controller
@RequestMapping("/equipment/deviceExample")
public class DeviceExampleController extends BaseController {
    @Autowired
    private DeviceExampleService deviceExampleService;

    @Autowired
    private DeviceBindingRelaService deviceBindingRelaService;

    @Autowired
    private HardwareService hardwareService;

    @Autowired
    private RedisDeviceService redisDeviceService;

    @GetMapping()
    @RequiresPermissions("equipment:deviceExample:deviceExample")
    String DeviceExample() {
        return "equipment/deviceExample/deviceExample";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("equipment:deviceExample:deviceExample")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<DeviceExampleDO> deviceExampleList = deviceExampleService.list(query);
        for (DeviceExampleDO d : deviceExampleList
                ) {
//			遍历查询绑定的设备
            Map<String, Object> map = new HashMap<>(1);
            map.put("devcieExampleId", d.getId());
            List<DeviceBindingRelaDO> list = deviceBindingRelaService.list(map);
            d.setBinding(list);
        }
        int total = deviceExampleService.count(query);
        PageUtils pageUtils = new PageUtils(deviceExampleList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("equipment:deviceExample:add")
    String add(Model model) throws Exception {
        //step1 查询设备名称
        List<HardwareDO> list = hardwareService.list(null);
        model.addAttribute("hardWareList", list);
        //step2 http获取所有管理数据
        model.addAttribute("deviceBindingRelaList", this.getAllBindList("http://192.168.31.15/device/getAllBindList"));
        return "equipment/deviceExample/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("equipment:deviceExample:edit")
    String edit(@PathVariable("id") Integer id, Model model) throws Exception {
        DeviceExampleDO deviceExample = deviceExampleService.get(id);
        Map<String, Object> mapRela = new HashMap<>(1);
        mapRela.put("devcieExampleId", id);
        List<DeviceBindingRelaDO> list = deviceBindingRelaService.list(mapRela);
        deviceExample.setBinding(list);
        model.addAttribute("deviceExample", deviceExample);
        //		查询设备名称
        List<HardwareDO> list1 = hardwareService.list(null);
        model.addAttribute("hardWareList", list1);
        model.addAttribute("deviceBindingRelaList", getAllBindCheckList(this.getAllBindList("http://192.168.31.15/device/getAllBindList"), list));
        return "equipment/deviceExample/edit";
    }


    private JSONArray getAllBindCheckList(JSONArray bindingRelaDTOList, List<DeviceBindingRelaDO> deviceBindingRelaDOList) {
        for (Iterator iterator = bindingRelaDTOList.iterator(); iterator.hasNext(); ) {
            JSONObject bindingRelaDTO = (JSONObject) iterator.next();
            for (DeviceBindingRelaDO deviceBindingRelaDO : deviceBindingRelaDOList) {
//							判断是否为同一个类型
                Integer bidingTypes = bindingRelaDTO.getInteger("bidingTypes");
                if (bidingTypes.equals(deviceBindingRelaDO.getBindingType())) {
//						遍历key是否等于我们绑定的id
                    JSONArray objects = bindingRelaDTO.getJSONArray("bindingDTOList");
                    for (Iterator iterator2 = objects.iterator(); iterator2.hasNext(); ) {
                        JSONObject bindingDTO = (JSONObject) iterator2.next();
                        String id = bindingDTO.getString("id");
                        if (id.equals(deviceBindingRelaDO.getDeviceBindingId())) {
//									设置选中状态
                            bindingDTO.put("checked", "0");
                        }
                    }
                }
            }
        }
        return bindingRelaDTOList;
    }


    /**
     * 获取数据来源方法
     * 需要通过http 获取数据
     *
     * @return
     */
    private JSONArray getAllBindList(String urlPath) throws Exception {
        return HttpClient.postJsonArray(urlPath, new JSONObject());
    }


    /**
     * 保存
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @RequiresPermissions("equipment:deviceExample:add")
    public R save(@RequestBody DeviceExampleDO deviceExampleDO) {
        deviceExampleDO.setCreateBy(getUsername());
        deviceExampleDO.setUpdateBy(getUsername());
        int save = deviceExampleService.save(deviceExampleDO);
        if (save > 0) {
            List<DeviceBindingRelaDO> binding = deviceExampleDO.getBinding();
            for (DeviceBindingRelaDO deviceBindingRelaDO : binding) {
                deviceBindingRelaDO.setDevcieExampleId(deviceExampleDO.getId());
                deviceBindingRelaService.save(deviceBindingRelaDO);
            }
            return R.ok();
        }

        //刷新redis缓存
        Map<String, String> param = new HashMap<>();
        param.put("id", deviceExampleDO.getId() + "");
        redisDeviceService.initDeviceData(param);
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("equipment:deviceExample:edit")
    public R update(@RequestBody DeviceExampleDO deviceExampleDO) {
//		更新
        deviceExampleService.update(deviceExampleDO);
//		解除绑定
        deviceExampleService.removeAll(deviceExampleDO.getId());
//		遍历绑定
        List<DeviceBindingRelaDO> binding = deviceExampleDO.getBinding();
        for (DeviceBindingRelaDO deviceBindingRelaDO : binding) {
            deviceBindingRelaDO.setDevcieExampleId(deviceExampleDO.getId());
            deviceBindingRelaService.save(deviceBindingRelaDO);
        }
        //刷新redis缓存
        Map<String, String> param = new HashMap<>();
        param.put("id", deviceExampleDO.getId() + "");
        redisDeviceService.initDeviceData(param);
        return R.ok();
    }

    /**
     * 修改
     */
    @ResponseBody
    @PostMapping("/validateByDeviceSn")
    public String validateByDeviceSn(String deviceSn) {
        Map<String, Object> map = new HashMap<>();
        map.put("deviceSn", deviceSn);
        List<DeviceExampleDO> list = deviceExampleService.list(map);
        if (list.size() > 0) {
            return "false";
        }
        return "true";
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("equipment:deviceExample:remove")
    public R remove(Integer id) {
        if (deviceExampleService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("equipment:deviceExample:batchRemove")
    public R remove(@RequestParam("ids[]") Integer[] ids) {
        deviceExampleService.batchRemove(ids);
        return R.ok();
    }
}
